package com.sita.tboard.hitchhike.search;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.sita.bike.R;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.support.LocationController;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.view.RecyclerItemClickListener;
import com.sita.tboard.hitchhike.bean.SelectedAddress;
import com.sita.tboard.util.AMapErrors;
import com.sita.tboard.util.TextUtils;
import com.sita.tboard.view.MyDividerItemDecoration;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.trinea.android.common.util.ToastUtils;

/**
 * AMapV1地图中简单介绍poisearch搜索
 */
public class PoiKeywordSearchActivity extends ActivityBase implements OnPoiSearchListener,
        RecyclerItemClickListener.OnItemClickListener, GeocodeSearch.OnGeocodeSearchListener {

    @Bind(R.id.type_address)
    AutoCompleteTextView searchTextView;// 输入搜索关键字

    @Bind(R.id.poi_result_list)
    RecyclerView poiListView;

    @Bind(R.id.toolbar)
    Toolbar toolbar;

    private String cityCode;// 要输入的城市名字或者城市区号
    private String keyword = null;
    private MaterialDialog progressDialog = null;// 搜索时进度条

    private PoiResult poiResult; // poi返回的结果
    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索

    private PoiKeywordSearchResultAdapter resultAdapter;
    private AtomicBoolean isFrom = new AtomicBoolean(false);
    private SelectedAddress selectedAddress;
    private GeocodeSearch mGeocoderSearch;

    public static Intent newIntent(boolean isFrom) {
        Intent intent = new Intent(GlobalContext.getGlobalContext(), PoiKeywordSearchActivity.class);
        intent.putExtra("isFrom", isFrom);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_poi_keyword_search);
        ButterKnife.bind(this);

        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle(null);
        toolbar.setNavigationIcon(R.mipmap.ic_back);

        boolean from = getIntent().getBooleanExtra("isFrom", true);
        isFrom.set(from);
        if (isFrom.get()) {
            searchTextView.setHint(R.string.begin);
        } else {
            searchTextView.setHint(R.string.end);
        }

        poiListView.setLayoutManager(new LinearLayoutManager(this));
        Drawable drawable = new ColorDrawable(getResources().getColor(R.color.divider_list));
        poiListView.addItemDecoration(new MyDividerItemDecoration(drawable, true, true));
        poiListView.setItemAnimator(new DefaultItemAnimator());

        resultAdapter = new PoiKeywordSearchResultAdapter();
        poiListView.setAdapter(resultAdapter);
        //resultAdapter.setOnItemClickListener(this);
        poiListView.addOnItemTouchListener(new RecyclerItemClickListener(PoiKeywordSearchActivity.this,
                this));

        cityCode = LocationController.getLastKnownLocation().getCityCode();

        selectedAddress = new SelectedAddress();

        searchTextView.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                keyword = TextUtils.checkEditText(searchTextView);
                if (!android.text.TextUtils.isEmpty(keyword)) {
                    doSearchQuery();
                }
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery() {
        progressDialog = new MaterialDialog.Builder(this)
                .content(R.string.searching)
                .progress(true, 10000).build();
        progressDialog.show();

        query = new PoiSearch.Query(keyword, "", cityCode);
        /*
        query - 查询字符串，多个关键字用“|”分割 。
        ctgr - POI 类型的组合，比如定义如下组合：餐馆|电影院|景点 （POI类型请在网站“相关下载”处获取）。
        city - 待查询城市（地区）的城市编码 citycode、城市名称（中文或中文全拼）、行政区划代码adcode。必设参数。
         */
        query.setPageSize(50);// 设置每页最多返回多少条poiitem
        poiSearch = new PoiSearch(this, query);
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    /**
     * POI信息查询回调方法
     */
    @Override
    public void onPoiSearched(PoiResult result, int rCode) {
        progressDialog.dismiss();// 隐藏对话框
        if (rCode == AMapErrors.SEARCH_SUCCESS) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiItem数据，页数从数字0开始

                    List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();
                    // 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

                    if (poiItems != null && poiItems.size() > 0) {
                        resultAdapter.addItems(poiItems);
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        String infomation = "推荐城市\n";
                        for (int i = 0; i < suggestionCities.size(); i++) {
                            infomation += "城市名称:" + suggestionCities.get(i).getCityName() + "城市区号:"
                                    + suggestionCities.get(i).getCityCode() + "城市编码:"
                                    + suggestionCities.get(i).getAdCode() + "\n";
                        }
                        ToastUtils.show(PoiKeywordSearchActivity.this, infomation);
                    } else {
                        ToastUtils.show(PoiKeywordSearchActivity.this, R.string.no_result);
                    }
                }
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem item, int rCode) {
    }

    @Override
    public void onItemClick(View view, int position) {
        PoiItem poiItem = resultAdapter.getItem(position);
        LatLonPoint latLonPoint = poiItem.getLatLonPoint();

        if (true) {
            selectedAddress.setCity(poiItem.getCityName())
                    .setProvince(poiItem.getProvinceName())
                    .setLatitude(latLonPoint.getLatitude())
                    .setLongitude(latLonPoint.getLongitude())
                    .setFullAddress(poiItem.getTitle());
            PoiSearchResultContainer.getInstance().setResult(isFrom.get(), selectedAddress);

            finish();
        } else {
            mGeocoderSearch = new GeocodeSearch(this);
            mGeocoderSearch.setOnGeocodeSearchListener(this);
            mGeocoderSearch.getFromLocationAsyn(new RegeocodeQuery(latLonPoint, 200, GeocodeSearch.AMAP));
        }
    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        if (i != AMapErrors.SEARCH_SUCCESS) {
            ToastUtils.show(this, AMapErrors.getErrorMsg(i));
        } else {
            LatLonPoint point = regeocodeResult.getRegeocodeQuery().getPoint();
            //获取数据
            RegeocodeAddress regeocodeAddress = regeocodeResult.getRegeocodeAddress();
            if (regeocodeAddress != null) {
                //Building = City = 深圳市Township = 香蜜湖街道District =福田区
                //Number = 78号Street = 紫竹六道Neighborhood = 竹盛花园Distance = 100.826
                //Building = 御花园海鲜食府City = 深圳市Township = 香蜜湖街道District =福田区
                //Number = 116号Street = 园博东街Neighborhood = Distance = 8.85065
                selectedAddress.setCity(regeocodeAddress.getCity())
                        .setProvince(regeocodeAddress.getProvince())
                        .setLatitude(point.getLatitude())
                        .setLongitude(point.getLongitude())
                        .setFullAddress(regeocodeAddress.getDistrict() + regeocodeAddress.getStreetNumber().getStreet() +
                                regeocodeAddress.getStreetNumber().getNumber() + regeocodeAddress.getBuilding());

                PoiSearchResultContainer.getInstance().setResult(isFrom.get(), selectedAddress);

                finish();
            } else {
                ToastUtils.show(this, AMapErrors.getErrorMsg(i));
                //设置数据空
                selectedAddress.empty();
            }
        }

    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

}
